<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

require_once APPPATH . 'models/m_select.php';

/**
 * Модель выборки видео
 *
 * @package CoreFramework
 * @version 1.0
 * @author Gennadiy Kozlenko
 */
class M_Select_Videos extends M_Select {
   
   /**
    * Букафка для поиска
    *
    * @var string
    */
   var $_char = '';
   
   /**
    * Конструктор класса
    *
    * @access public
    * @return M_Select_Videos
    */
   function M_Select_Videos() {
      parent::M_Select();
      $this->load->language('select_videos');
   } // end M_Select_Videos
   
   /**
    * Инициализация модельки
    *
    */
   function initialize() {
      // Устанавливаем запрос
      $sql = "
         SELECT
            v.id_video AS id,
            v.is_featured,
            v.title,
            '' AS preview,
            v.image AS image_hidden,
            v.orig_title AS orig_title_hidden,
            v.year AS year_hidden,
            v.length,
            num_torrents,
            ROUND(IF(v.num_ratings > 0, v.sum_ratings / v.num_ratings, 0), 2) AS rating,
            (
               SELECT
                  COUNT(*)
               FROM
                  " . $this->db->dbprefix('video_comments') . " c
               WHERE
                  v.id_video = c.id_video
               LIMIT
                  1
            ) AS comments,
            v.date_created,
            num_downloaded,
            v.status
         FROM
            " . $this->db->dbprefix('videos') . " v
         WHERE
            v.status <> 'deleted'
      ";
      if (!empty($this->_char)) {
         $sql .= "
            AND v.title LIKE '" . $this->db->escape_str($this->_char) . "%'
         ";
      }
      parent::set_sql($sql);
   }
   
   /**
    * Установка букафки
    *
    * @param string $char
    */
   function set_char($char) {
      $this->_char = $char;
   }
   
   /**
    * Обработка результата
    *
    * @access protected
    * @param array $result
    */
   function _process_result(&$result) {
      if (!empty($result['orig_title_hidden'])) {
         $result['title'] .= ' / ' . $result['orig_title_hidden'];
      }
      if (!empty($result['year_hidden'])) {
         $result['title'] .= ' (' . $result['year_hidden'] . ')';
      }
      $result['title'] = anchor(create_link('video', 'index', array('id' => $result['id'])), $result['title'], 'target="_blank"');
      $result['is_featured'] = $this->lang->line('videos_is_featured_' . $result['is_featured']);
      $result['num_torrents'] = anchor(create_link('admin_manage_torrents', 'index', array('video' => $result['id'])), $result['num_torrents']);
      
      if (!empty($result['image_hidden'])) {
         $result['preview'] = str_replace(array('{%id%}', '{%image%}'), array($result['id'], $result['image_hidden']), $this->lang->line('videos_preview'));
      }
      $this->_fields['preview']['sort'] = false;
   } // end _process_result
   
}
